<?php

namespace App\Admin\Controllers;

use App\Admin\Repositories\UserCard;
use App\Models\CardNum;
use App\Models\CardType;
use App\Models\User;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;

class UserCardController extends AdminController
{
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new UserCard(['user','card']), function (Grid $grid) {
            $grid->column('id')->sortable();
            $grid->column('user.username','用户名');
            $grid->column('card.name','卡名');
            $grid->column('dense','密钥');
            $grid->column('status')->using([1=>'启用',0=>'禁用'])->label([
                1=>'success',
                0=>'danger'
            ]);
            $grid->column('created_at','绑卡时间');
            $grid->column('updated_at');

            $grid->filter(function (Grid\Filter $filter) {
                $filter->equal('id');

            });
        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new UserCard(), function (Show $show) {
            $show->field('id');
            $show->field('user_id');
            $show->field('card_id');
            $show->field('dense');
            $show->field('status');
            $show->field('created_at');
            $show->field('updated_at');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new UserCard(), function (Form $form) {
            $form->display('id');
            $form->select('user_id')->options(User::pluck('username', 'id'));
            $form->hidden('card_id');
            $form->text('dense','密钥');
            $form->radio('status')->options([1 => '启用', 0 => '禁用'])->default(1);

            $form->display('created_at');
            $form->display('updated_at');
        })->saving(function (Form $form) {
            $keys=CardNum::query()->where('key',$form->dense)->first();
            if (is_null($keys)){
                return $form->response()->error('密钥不存在');
            }
            $form->card_id=$keys->card_id;
            $usercardmodel=\App\Models\UserCard::query()->where('user_id',$form->user_id)->orWhere('dense',$form->dense)->first();
            if (!is_null($usercardmodel)){
                return $form->response()->error('该密钥或者用户已经被绑定');
            }
        })->saved(function (Form $form) {
            $keys=CardNum::query()->where('key',$form->dense)->first();
            $keys->status=1;
            $keys->save();
        });
    }
}
